package cn.net.sichen.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * json 工具类
 */
public class JsonUtils {

    public static String objToJson(Object obj) {
        ObjectMapper mapper = new ObjectMapper();

        String json = "";
        //类转JSON
        try {
            json = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return json;
    }

    /**
     * json转成对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T jsonToObj(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();

        //类转JSON
        T t = null;
        try {
            t = mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }


    /**
     * json转成集合对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToList(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();

        //类转JSON
        List<T> list = null;
        try {
            list = mapper.readValue(json, new TypeReference<List<T>>() {});
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
